public class CPUTest {

    public static void main(String[] args) {
        int numCores = Runtime.getRuntime().availableProcessors();
        int targetThreads = numCores / 2;
        for (int i = 0; i < targetThreads; i++) {
            Thread thread = new Thread(new CpuTask());
            thread.start();
        }
    }

    static class CpuTask implements Runnable {
        @Override
        public void run() {
            long busyTime = 5_000_000; // 5 毫秒的计算时间
            long idleTime = 4_000_000;   // 4 毫秒的休眠时间
            while (true) {
                // 计算任务：占用 CPU
                long startTime = System.nanoTime();
                while ((System.nanoTime() - startTime) < busyTime) {
                    // 空循环，占用 CPU
                }
                // 休眠：释放 CPU
                try {
                    Thread.sleep(idleTime / 1_000_000); // 将纳秒转换为毫秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
